package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    GeneratePageService generatePageService;
    @Value("${file.minio.readPath}")
    String readPath;

    @Autowired
    RabbitTemplate rabbitTemplate;


    @Transactional
    @Override
    public void publishArticle(Integer newsId) {
        // 1. 基于feign查询自媒体文章数据
        WmNews wmNews = getWmNews(newsId);
        // 2. 封装成ApArticle
        ApArticle apArticle = getApArticle(wmNews);
        // 3. 保存或修改文章 (id)   wmNews ==> ap_article
        saveOrUpdateApArticle(apArticle);
        // 4. 保存  配置信息 和  内容信息
        saveConfigAndContent(apArticle,wmNews);
        // 5. 页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(),apArticle);
        // 6. 修改wmNews 状态 9   及   关联article_id
        wmNews.setStatus((short)9);
        wmNews.setArticleId(apArticle.getId());
        ResponseResult newsResult = wemediaFeign.updateWmNews(wmNews);
        if (newsResult.getCode().intValue()!=0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        // 7. mq 通知索引库更新索引
        rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE, apArticle.getId());

    }

    @Autowired
    ApArticleMapper apArticleMapper;


    @Autowired
    RedisTemplate redisTemplate;

    @Value("${file.oss.web-site}")
    private String webSite;

    /**
     * 根据参数加载文章列表
     * @param loadtype  0为加载更多  1为加载最新
     * @param dto
     * @param firstPage 是否为首页 true 首页
     * @return
     */
    @Override
    public ResponseResult load2(Short loadtype, ArticleHomeDTO dto, boolean firstPage) {

        if (firstPage) {
            // redis
            String articleListJson = (String) redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(articleListJson)) {
                List<ApArticle> apArticles = JSON.parseArray(articleListJson, ApArticle.class);
                for (ApArticle apArticle : apArticles) {
                    apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
                }

                ResponseResult result = ResponseResult.okResult(apArticles);
                result.setHost(webSite);

                return result;
            }
        }

        return load(loadtype, dto);
    }

    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        // 1. 校验参数
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        if (dto.getSize() == null) {
            dto.setSize(10);
        }
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        // 2. 调用mapper查询
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);

        for (ApArticle apArticle : apArticles) {
            apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
        }

        // 3. 封装返回结果
        return ResponseResult.okResult(apArticles);
    }

    private void saveConfigAndContent(ApArticle apArticle, WmNews wmNews) {
        // 1.保存配置
        ApArticleConfig config = new ApArticleConfig();
        config.setArticleId(apArticle.getId());
        config.setIsComment(true);
        config.setIsForward(true);
        config.setIsDown(false);
        config.setIsDelete(false);
        apArticleConfigMapper.insert(config);
        // 2. 保存文章内容
        ApArticleContent content = new ApArticleContent();
        content.setArticleId(apArticle.getId());
        content.setContent(wmNews.getContent());
        apArticleContentMapper.insert(content);
    }

    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    ApArticleContentMapper apArticleContentMapper;

    /**
     * 保存或修改文章
     * @param apArticle
     */
    private void saveOrUpdateApArticle(ApArticle apArticle) {
        if(apArticle.getId() == null){
            // 保存文章
            apArticle.setCollection(0); // 收藏
            apArticle.setComment(0); // 评论
            apArticle.setLikes(0); // 点赞
            apArticle.setViews(0); // 阅读
            apArticle.setCreatedTime(new Date());
            save(apArticle);
        }else {
            // 修改文章
            ApArticle byId = getById(apArticle.getId());
            if (byId == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的文章信息不存在");
            }
            updateById(apArticle);
            // 删除关联配置信息
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId,apArticle.getId()));
            // 删除关联内容信息
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId,apArticle.getId()));
        }
    }

    @Autowired
    AdminFeign adminFeign;
    @Autowired
    AuthorMapper authorMapper;



    private ApArticle getApArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(wmNews,apArticle);
        apArticle.setId(wmNews.getArticleId()); // 设置文章id
        apArticle.setFlag((byte)0);
        apArticle.setLayout(wmNews.getType());
        // 频道信息
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());
        if (channelResult.getCode().intValue()!=0) {
            log.error(" 文章发布失败   原因: 远程调用查询频道信息失败   {} ",channelResult.getErrorMessage());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用查询频道失败");
        }
        AdChannel channel = channelResult.getData();
        if(channel == null){
            log.error(" 文章发布失败   原因: 未查询到相关频道信息  文章id:   {} , 频道id: {}",wmNews.getId(),wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到自媒体文章");
        }
        apArticle.setChannelName(channel.getName());
        // 作者信息
        ApAuthor author = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        if(author == null){
            log.error(" 文章发布失败   原因: 未查询到相关作者信息  文章id:   {} , 自媒体用户id: {}",wmNews.getId(),wmNews.getUserId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到相关作者信息");
        }
        apArticle.setAuthorId(Long.valueOf(author.getId()));
        apArticle.setAuthorName(author.getName());
        return apArticle;
    }

    @Autowired
    WemediaFeign wemediaFeign;

    private WmNews getWmNews(Integer newsId) {
        // 1. 远程查询自媒体文章
        ResponseResult<WmNews> newsResult = wemediaFeign.findWmNewsById(newsId);
        // 2. 判断是否存在
        if (newsResult.getCode().intValue()!=0) {
            log.error(" 文章发布失败   原因: 远程调用自媒体文章查询失败   {} ",newsResult.getErrorMessage());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程查询自媒体文章失败");
        }
        WmNews wmNews = newsResult.getData();
        if(wmNews == null){
            log.error(" 文章发布失败   原因: 未查询到自媒体文章信息  文章id:   {} ",newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到自媒体文章");
        }
        // 3. 检查状态  是否为 4 或 8
        Short status = wmNews.getStatus();
        if (!WemediaConstants.WM_NEWS_AUTH_PASS.equals(status) && !WemediaConstants.WM_NEWS_AUTHED_STATUS.equals(status)) {
            log.info(" 文章发布失败   原因: 文章状态不是 8 或 4     文章id:   {} ",newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章状态错误");
        }
        return wmNews;
    }
}
